//
//  NetworkHandler.m
//  UI21_04_Block 实现网络请求回调
//
//  Created by 李劲成 on 16/4/7.
//  Copyright © 2016年 ljc. All rights reserved.
//

#import "NetworkHandler.h"

@implementation NetworkHandler

// core API
+ (void)networkHandlerGetWithURL:(NSString *)urlString completionHandler:(void(^)(id result, NSURLResponse *response, NSError *error))block{
    
    // url 中只支持 ASCII码 ,如果出现中文需要进行转码.
    // url 中的中文一般出现在查询部分, 所以将查询部分进行转码.
    NSString *newString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    // Session
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:newString];
    // session 添加任务
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 数据解析
        if (data) {
        id result1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 通过 block 回调(调用)
            block(result1, response, error);
            
        });
       }
    }];
    [task resume];
    
}


+ (void)networkHandlerPostWithURL:(NSString *)urlString Arguments:(NSString *)arguments completionHandler:(void (^)(id, NSURLResponse *, NSError *))block {
    // 转换 URL
    NSString *newString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:newString];
    
    //Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSData *data = [arguments dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPMethod = @"POST";
    request.HTTPBody = data;
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        if (data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                block(result, response, error);
                
            });
            
        }
        
    }];
    
    [task resume];
}


@end
